<template>
  <ElDialog
    v-model="dialogVisible"
    :title="dialogType === 'add' ? '添加用户' : '编辑用户'"
    width="30%"
    align-center
  >
    <ElForm ref="formRef" :model="formData" :rules="rules" label-width="80px">
      <ElFormItem label="用户名" prop="username">
        <ElInput v-model="formData.username" placeholder="请输入用户名" />
      </ElFormItem>
      <ElFormItem label="昵称" prop="nick_name">
        <ElInput v-model="formData.nick_name" />
      </ElFormItem>
      <ElFormItem label="手机号" prop="phone">
        <ElInput v-model="formData.phone" placeholder="请输入手机号" />
      </ElFormItem>
      <ElFormItem label="邮箱" prop="email">
        <ElInput v-model="formData.email" />
      </ElFormItem>
      <ElFormItem label="性别" prop="gender">
        <ElSelect v-model="formData.gender">
          <ElOption label="男" value="男" />
          <ElOption label="女" value="女" />
        </ElSelect>
      </ElFormItem>
      <ElFormItem label="角色" prop="role">
        <ElSelect v-model="formData.role" multiple>
          <ElOption
            v-for="role in roleList"
            :key="role.roleCode"
            :value="role.roleCode"
            :label="role.roleName"
          />
        </ElSelect>
      </ElFormItem>
    </ElForm>
    <template #footer>
      <div class="dialog-footer">
        <ElButton @click="dialogVisible = false">取消</ElButton>
        <ElButton type="primary" @click="handleSubmit">提交</ElButton>
      </div>
    </template>
  </ElDialog>
</template>

<script setup lang="ts">
  import { ROLE_LIST_DATA } from '@/mock/temp/formData'
  import type { FormInstance, FormRules } from 'element-plus'
  import { fetchGetUserInfo, fethcAddUser } from '@/api/system-manage'

  interface Props {
    visible: boolean
    type: string
    userData?: Partial<Api.SystemManage.UserListItem>
  }

  interface Emits {
    (e: 'update:visible', value: boolean): void
    (e: 'submit'): void
  }

  const props = defineProps<Props>()
  const emit = defineEmits<Emits>()

  // 角色列表数据
  const roleList = ref(ROLE_LIST_DATA)

  // 对话框显示控制
  const dialogVisible = computed({
    get: () => props.visible,
    set: (value) => emit('update:visible', value)
  })

  const dialogType = computed(() => props.type)

  // 表单实例
  const formRef = ref<FormInstance>()

  // 表单数据
  const formData = reactive({
    username: '',
    nick_name: '',
    phone: '',
    email: '',
    gender: '男',
    role: [] as string[]
  })

  // 表单验证规则
  const rules: FormRules = {
    username: [
      { required: true, message: '请输入用户名', trigger: 'blur' },
      { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
    ],
    nick_name: [
      { required: true, message: '昵称不能为空', trigger: 'blur' },
      { max: 20, message: '昵称不能超过20个字符', trigger: 'blur' }
    ],
    phone: [
      { required: true, message: '请输入手机号', trigger: 'blur' },
      { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
    ],
    gender: [{ required: true, message: '请选择性别', trigger: 'blur' }],
    // email: [
    //   { required: true, message: '邮箱不能为空', trigger: 'blur' },
    //   {
    //     pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
    //     message: '请输入正确的邮箱格式（如：xxx@xxx.com）',
    //     trigger: 'blur'
    //   }
    // ],
    role: [{ required: true, message: '请选择角色', trigger: 'blur' }]
  }

  /**
   * 初始化表单数据
   * 根据对话框类型（新增/编辑）填充表单
   */
  const initFormData = async () => {
    console.log('================初始化表单===============' + dialogType.value + props.userData)
    Object.assign(formData, {
      username: '',
      nick_name: '',
      phone: '',
      email: '',
      gender: '男',
      role: []
    })

    if (dialogType.value === 'edit' && props.userData) {
      let { id = 0 } = props.userData

      const res = await fetchGetUserInfo(id)

      // 填充表单（与后台返回字段对齐，示例：res.data为用户详情）
      console.log(res)

      // 填充表单（与后台返回字段对齐，示例：res.data为用户详情）
      Object.assign(formData, {
        username: res.username || '',
        nick_name: res.nick_name || '', // 补充昵称赋值
        phone: res.phone || '',
        email: res.email || '', // 补充邮箱赋值
        gender: res.gender || '男'
        // role: res.userRoles ? (Array.isArray(res.data.userRoles) ? res.data.userRoles : []) : [] // 角色映射
      })

    }

    // const isEdit = props.type === 'edit' && props.userData
    // const row = props.userData

    // Object.assign(formData, {
    //   username: isEdit && row ? row.username || '' : '',
    //   phone: isEdit && row ? row.phone || '' : '',
    //   gender: isEdit && row ? row.gender || '男' : '男',
    //   role: isEdit && row ? (Array.isArray(row.roles) ? row.roles : []) : []
    // })
  }

  /**
   * 监听对话框状态变化
   * 当对话框打开时初始化表单数据并清除验证状态
   */
  watch(
    () => [props.visible, props.type, props.userData],
    ([visible]) => {
      if (visible) {
        initFormData()
        nextTick(() => {
          formRef.value?.clearValidate()
        })
      }
    },
    { immediate: true }
  )

  /**
   * 提交表单
   * 验证通过后触发提交事件
   */
  const handleSubmit = async () => {
    if (!formRef.value) return

    // 验证表单
    await formRef.value.validate()

    if (dialogType.value === 'add') {
      await fethcAddUser(formData)
      ElMessage.success('添加成功')
    } else {
      ElMessage.success('更新成功')
    }

    dialogVisible.value = false
    emit('submit')

    // await formRef.value.validate((valid) => {
    //   if (valid) {
    //     ElMessage.success(dialogType.value === 'add' ? '添加成功' : '更新成功')
    //     dialogVisible.value = false
    //     emit('submit')
    //   }
    // })
  }
</script>
